package com.hitqz.robot.biz.controller;

import com.hitqz.robot.common.core.util.R;
import com.hitqz.robot.biz.websocket.endpoint.LiveEndpoint;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Cleanup;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;
import java.nio.ByteBuffer;

/**
 * 推流
 *
 * @author wengyongxin
 * @date 2024-05-26 09:21:06
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/rtsp" )
@Tag(description = "rtsp" , name = "视频流管理" )
@Slf4j
public class RtspController {

    @GetMapping("/ws/{sourceKey}" )
    public R receive(HttpServletRequest request, @PathVariable(value = "sourceKey") String sourceKey){
		try {
			@Cleanup
			InputStream inputStream = request.getInputStream();
			ByteBuffer buffer = ByteBuffer.allocateDirect(4096); // 分配直接缓冲区
			int length;
			while (true) {
				length = inputStream.read(buffer.array());
				if (length == -1) {
					log.info("流结束");
					break; // 流结束，退出循环
				}
				if (length > 0) {
					// 注意：这里应该使用实际读取的长度来限制ByteBuffer
					buffer.limit(length);
					LiveEndpoint.sendVideoData(sourceKey, buffer);
					buffer.clear(); // 为下一次读取准备缓冲区
				}
			}
		}catch (Exception e){
			log.error("推流输出错误",e);
			return R.failed("推流输出错误");
		}
		return R.ok();
    }

}